<?php
require_once("User.php");
$db_connect = mysqli_connect("localhost", "root", "", "battleofthemages");
session_start();

if($_POST['action'] == "insert"){
	$user = unserialize($_SESSION['user']);
	$username = $user->getUsername();
	$userQuery = "SELECT user_id FROM user WHERE username=\"$username\"";
	$result = mysqli_query($db_connect, $userQuery);
	if(mysqli_num_rows($result) > 0){
		$row = mysqli_fetch_assoc($result);
		$user_id = $row['user_id'];
	}

	$line = $_POST['line'];
	$lineQuery = "INSERT INTO `chat`(`user_id`, `value`) VALUES ($user_id,\"$line\")";
	mysqli_query($db_connect, $lineQuery);
	echo "$user_id $line";
}else if($_POST['action'] == "refresh"){
	$lines = array();

	$clearQuery = "DELETE FROM chat WHERE date_sent < date_Add(now(), interval - 24 hour)";
	mysqli_query($db_connect, $clearQuery);

	$queryParagraphs = "SELECT u.username as name, value, cast(date_sent as time) as time FROM chat c INNER JOIN user u on c.user_id=u.user_id ORDER BY time";
	$resultParagraphs = mysqli_query($db_connect, $queryParagraphs);
	if(mysqli_num_rows($resultParagraphs) > 0){
		while($row = mysqli_fetch_assoc($resultParagraphs)){
			$lines[] = "<p><span id=\"uname\">" . $row['name'] . " </span><span id=\"time\"> " . $row['time'] . "</span> " . $row['value'] . "</p>";
		}
	}
	echo json_encode($lines);
}else {
	echo "error";
}

mysqli_close($db_connect);
?>